package com.atomikos.test;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.jdbc.AtomikosDataSourceBean;

import javax.transaction.SystemException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author mdl
 * @date 2020/4/26 11:23
 */
public class Main {

    private static AtomikosDataSourceBean createAtomikosDataSourceBean(String dbName){
        Properties p =new Properties();
        p.setProperty("url", "jdbc:mysql://localhost:3306/"+dbName+"?serverTimezone=UTC&characterEncoding=utf-8");
        p.setProperty("user", "root");
        p.setProperty("password", "123456");

        AtomikosDataSourceBean ds =new AtomikosDataSourceBean();
        ds.setUniqueResourceName(dbName);
        ds.setXaDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
        ds.setXaProperties(p);
        return ds;
    }

    public static void main(String[] args) {
        // 准备数据源
        AtomikosDataSourceBean ds1 = createAtomikosDataSourceBean("ymorder");
        AtomikosDataSourceBean ds2 = createAtomikosDataSourceBean("stock");

        Connection conn1 =null;
        Connection conn2 =null;

        PreparedStatement ps1 =null;
        PreparedStatement ps2 =null;

        UserTransactionImp userTransaction = new UserTransactionImp();
        try {
            // 开启事务
            userTransaction.begin();

            conn1 =ds1.getConnection();
            ps1 = conn1.prepareStatement("insert into ymorder.order(user_id, state, sku_id) values(?, ?, ?)");
            ps1.setInt(1, 77);
            ps1.setInt(2, 2);
            ps1.setInt(3, 1000);
            ps1.executeUpdate();

            conn2 =ds2.getConnection();
            ps2 = conn2.prepareStatement("insert into stock.stock(sku_id, count) values(?, ?)");
            ps2.setInt(1, 1000);
            ps2.setInt(2, 2);
            ps2.executeUpdate();

            userTransaction.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                userTransaction.rollback();
            } catch (SystemException e) {
                e.printStackTrace();
            }
        }

    }
}
